import { useEffect, useImperativeHandle, useState, type MutableRefObject } from 'react';
import { Avatar, Checkbox, Form, Input, Spin, TreeSelect } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { SelectUserStyle } from './style';
import { selectUnitList, selectDeptList, selectUserList } from '../../http/system-config';
import { serverURL, userInfo } from '../../config';
import { handleTree } from '@/utils/array';
import type { MembersRes } from '../../http/chatting-group-members';
import type { SearchProps } from 'antd/es/input';
import type { CheckboxGroupProps } from 'antd/es/checkbox';

interface UserInfo {
	id: number;
	realname: string;
	avatar: string;
	inGroup: boolean;
}
export interface SelectUserRef {
	selectedUsers: UserInfo[];
}
type SelectUserProps = {
	membersList: MembersRes[];
	comRef: MutableRefObject<SelectUserRef>;
};
const SelectUser = (props: SelectUserProps) => {
	const { membersList, comRef } = props;

	// 单位
	const [unitList, setUnitList] = useState([]);
	const [unitSelected, setUnitSelected] = useState<number>();
	// 部门
	const [deptList, setDeptList] = useState([]);
	const [deptSelected, setDeptSelected] = useState<number>();
	// 用户
	const [loading, setLoading] = useState(true);
	const [userList, setUserList] = useState<UserInfo[]>([]);
	const [selectedUsersId, setSelectedUsersId] = useState<number[]>([]);
	const [selectedUsers, setSelectedUsers] = useState<UserInfo[]>([]);
	// 用户名
	const [userName, setUserName] = useState<string>(null);

	// 查询单位列表
	const queryUnitList = async () => {
		const { data } = await selectUnitList({});
		const newList = handleTree(data);
		setUnitList(newList);
		const currentUnit = data.find((item) => item.id === userInfo.unitId);
		if (currentUnit) {
			setUnitSelected(currentUnit.id);
		} else if (data.length) {
			setUnitSelected(data[0].id);
		}
	};
	useEffect(() => {
		queryUnitList();
	}, []);

	// 查询部门列表
	const queryDeptList = async () => {
		const { data } = await selectDeptList({ unitId: unitSelected });
		const newList = handleTree(data);
		setDeptList(newList);
		if (data.length) {
			setDeptSelected(data[0].id);
		}
	};
	useEffect(() => {
		if (unitSelected) queryDeptList();
	}, [unitSelected]);

	// 查询用户列表
	const queryUserList = async (username?: string) => {
		setLoading(true);
		const { data } = await selectUserList({
			departmentId: deptSelected,
			username
		}).finally(() => setLoading(false));
		const useList =
			data?.map((item) => {
				if (item.id !== userInfo.id) {
					return {
						id: item.id,
						avatar: item.headUrl,
						realname: item.realname,
						inGroup: membersList.findIndex((member) => item.id === member.userId) !== -1
					};
				} else {
					return null;
				}
			}) ?? [];
		setUserList(useList);
		const selected = selectedUsers
			.filter((item) => data.find((user) => user.id === item.id))
			.map((item) => item.id);
		setSelectedUsersId(selected);
	};
	useEffect(() => {
		if (deptSelected) queryUserList();
	}, [deptSelected]);

	// 用户名搜索
	const handleSearch: SearchProps['onSearch'] = (value) => {
		queryUserList(value || undefined);
	};

	// 选择用户
	const handleSelectUser: CheckboxGroupProps<number>['onChange'] = (values) => {
		setSelectedUsersId(values);
	};
	const handleUserClick = (user: UserInfo) => {
		const newList = [...selectedUsers];
		const index = newList.findIndex((item) => item.id === user.id);
		if (index === -1) {
			newList.push(user);
		} else {
			newList.splice(index, 1);
		}
		setSelectedUsers(newList);
	};

	// 删除已选择的用户
	const handleDelUser = (user: UserInfo, index: number) => {
		const newUsersList = [...selectedUsers];
		const newUsersId = [...selectedUsersId];
		const findIndex = newUsersId.findIndex((id) => id === user.id);
		if (findIndex !== -1) {
			newUsersId.splice(findIndex, 1);
			setSelectedUsersId(newUsersId);
		}
		newUsersList.splice(index, 1);
		setSelectedUsers(newUsersList);
	};

	useImperativeHandle(comRef, () => ({ selectedUsers }));

	return (
		<SelectUserStyle is_del={false}>
			<div className="select_unit_dept">
				<Form.Item labelCol={{ style: { width: '60px' } }} style={{ width: '50%' }}>
					<TreeSelect
						placeholder="请选择单位"
						fieldNames={{ value: 'id', label: 'unitName' }}
						value={unitSelected}
						treeData={unitList}
						onChange={(value) => {
							setUnitSelected(value);
							setUserName(null);
						}}
					/>
				</Form.Item>
				<Form.Item labelCol={{ style: { width: '60px' } }} style={{ width: '50%' }}>
					<TreeSelect
						placeholder="请选择部门"
						fieldNames={{ value: 'id', label: 'deptName' }}
						value={deptSelected}
						treeData={deptList}
						onChange={(value) => {
							setDeptSelected(value);
							setUserName(null);
						}}
					/>
				</Form.Item>
			</div>
			<div className="select_user">
				<div className="left_select">
					<div className="search_name">
						<Input.Search
							allowClear
							placeholder="请输入用户名"
							value={userName}
							onChange={(evt) => setUserName(evt.target.value)}
							onSearch={handleSearch}
						/>
					</div>
					<Spin wrapperClassName="user_list" spinning={loading}>
						<div className="user_list">
							<Checkbox.Group value={selectedUsersId} onChange={handleSelectUser}>
								{userList.map((item) => (
									<div key={item.id} className="user_item">
										<Checkbox
											value={item.id}
											disabled={item.inGroup}
											onClick={() => handleUserClick(item)}
										>
											<div className="item">
												<Avatar size={35} shape="square" src={serverURL + item.avatar} />
												<div className="user_name">{item.realname}</div>
											</div>
										</Checkbox>
									</div>
								))}
							</Checkbox.Group>
						</div>
					</Spin>
				</div>
				<div className="right_selected">
					{selectedUsers.map((item, index) => (
						<div key={item.id} className="item_info">
							<Avatar
								className="item_avatar"
								shape="square"
								size={45}
								src={serverURL + item.avatar}
							/>
							<div className="item_name">{item.realname}</div>
							<div className="del_btn" onClick={() => handleDelUser(item, index)}>
								<CloseOutlined />
							</div>
						</div>
					))}
				</div>
			</div>
		</SelectUserStyle>
	);
};

export default SelectUser;
